//资产管理计划
import React from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, TreeSelect } from 'antd';
import { TableC, AdvancedSearch, PrimaryC, DATA_ENTRY, ModalC, FormGroup, codeType, ExportC } from '../../../../comps';
import moment from 'moment';

import myStyle from '../index.less';
//组件
import RightInfo from '../shareComp/rightInfo';
import TipsInfo from '../shareComp/tipInfo';
const formItemLayoutDefine = {
  labelCol: {
    xs: { span: 6, offset: 0 },
    sm: { span: 6, offset: 0 },
    md: { span: 6, offset: 0 },
    lg: { span: 6, offset: 0 },
    xl: { span: 6, offset: 0 },
    xxl: { span: 6, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 18, offset: 0 },
    sm: { span: 18, offset: 0 },
    md: { span: 18, offset: 0 },
    lg: { span: 18, offset: 0 },
    xl: { span: 18, offset: 0 },
    xxl: { span: 18, offset: 0 },
  },
};
class AssetManagePlanInfo extends React.Component {
  constructor() {
    super();
    this.state = {
      searchObj: {}, // 查询的条件
      currentPage: 1, // 页码
      numInPage: 10, // 一页展示数量
      total: 0, // 表格总数
      columns: [
        {
          title: '证券代码',
          dataIndex: 'tradingCode',
          key: 'tradingCode',
        },
        {
          title: '证券名称',
          dataIndex: 'tradingName',
          key: 'tradingName',
        },
        {
          title: '资产类别',
          dataIndex: 'assetType',
          key: 'assetType',
        },
        {
          title: '租户',
          dataIndex: 'tenant',
          key: 'tenant',
        },
      ], // 表格头
      dataSource: [], // 表格数据
      isReset: false, // 是否点击重置
      selectedRowKeys: [], // 表格checkbox选择
      selectedRows: [], // 表格checkbox选择
      isBatchConfirmation: false, // 批量确认按钮置灰
      pageType: '', // 编辑/新增字段
      count: undefined, //与资讯不一致的条数
      flag: '1', //1全部 2不一致
      addedThisMonth: 0, //本月新增条数
      isHistory: false, //是否是历史日期
      holdDataList: [], //持仓日期下拉
      latestholdDate: '', //最新的持仓日期
    };
  }

  componentDidMount() {
    //查询持仓日期
    this.props.dispatch({
      type: 'bondInformationM/queryHoldDataList',
      payload: {},
      callback: (data) => {
        if (data) {
          let temp = [];
          data.map((item) => {
            temp.push({
              value: item,
              title: item,
            });
          });
          //设置默认值为最新的持仓日期 其余下拉日期为历史日期
          this.AdvancedSearchRef?.props.form?.setFieldsValue({
            holdDate: data.length ? data[0] : undefined,
          });
          let obj = this.state.searchObj;
          obj.holdDate = data.length ? data[0] : undefined;
          this.setState(
            {
              holdDataList: [...temp],
              searchObj: { ...obj },
              latestholdDate: data.length ? data[0] : undefined, ////保存最新的持仓
            },
            () => {
              this.getTableData();
            },
          );
        } else {
          this.setState({ holdDataList: [] });
        }
      },
    });
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.tenant != this.props.tenant) {
      this.getTableData();
    }
  }

  //查询
  onQuery = (e) => {
    //如果子查询还在 不可以点击查询按钮
    if (this.state.flag != '1') {
      message.warning('请点击与资讯不一致提示语句，取消查询后重试！');
      return;
    }
    // 判断是历史数据还是当前数据
    if (this.AdvancedSearchRef) {
      if (this.state.latestholdDate != this.AdvancedSearchRef.props.form.getFieldValue('holdDate')) {
        this.setState({
          flag: '1', //历史数据 永远查询全部
        });
      }
      this.setState({
        isHistory: this.state.latestholdDate == this.AdvancedSearchRef.props.form.getFieldValue('holdDate') ? false : true,
      });
    }
    this.setState(
      {
        searchObj: e,
        isReset: false, // 是否点击重置
        currentPage: 1, // 页码
        numInPage: 10, // 一页展示数量
        selectedRowKeys: [], // 表格checkbox选择
        selectedRows: [], // 表格checkbox选择
        isBatchConfirmation: false, // 批量确认按钮置灰
      },
      () => {
        this.getTableData();
      },
    );
  };

  //重置
  onClear = () => {
    this.setState({
      isReset: true,
    });
    //重置日期
    this.AdvancedSearchRef?.props.form?.setFieldsValue({
      holdDate: this.state.latestholdDate,
    });
    //租户也重置
    this.props.resetTenant();
  };

  //表格分页切换
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    const { isReset } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.getTableData();
      },
    );
  };
  // 获取表格数据
  getTableData = () => {
    const { currentPage, numInPage, searchObj } = this.state;
    this.setState(
      {
        dataSource: undefined,
      },
      () => {
        this.props.dispatch({
          type: 'manAssetManagePlanInfoM/getDataList',
          payload: {
            ...searchObj,
            currentPage: currentPage,
            numInPage: numInPage,
            flag: this.state.flag,
            tenant: this.props.tenant, //租户入参
          },
          callback: (data) => {
            this.setState({
              dataSource: data.dataSource,
              count: data.count,
              addedThisMonth: data.addedThisMonth || 0,
              total: data.pageInfo?.total,
              currentPage: data.pageInfo?.currentPage,
              numInPage: data.pageInfo?.numInPage,
            });
          },
        });
      },
    );
  };

  //新增/编辑弹窗
  addModalOpen = (type, record) => {
    this.setState(
      {
        pageType: type,
        visible: true,
      },
      () => {
        if (type == 'edit') {
          setTimeout(() => {
            const {
              form: { setFieldsValue },
            } = this.formGroupThis.props;

            this.setState({
              id: record.id,
              tradingCode: record.tradingCode,
            });
            this.formGroupThis.setSelect(record.exchangeCode + '-' + record.tradingCode);

            setFieldsValue({
              assetType: record.assetType,
              isWeiWai: record.isWeiWai,
            });
          }, 0);
        }
      },
    );
  };

  //批量确认
  confirm = () => {
    //点击批量确认的时候，前端需要判断有几条数据待补充，并且做出提示
    if (this.state.selectedRows.filter((item) => item.isSuppleInfo == '1')?.length) {
      message.warning(`您有${this.state.selectedRows.filter((item) => item.isSuppleInfo == '1').length}条信息待补充`);
      return false;
    }
    this.props.dispatch({
      type: 'manAssetManagePlanInfoM/assetManagePlanInfoConfirm',
      payload: { data: this.state.selectedRowKeys },
      callback: (res) => {
        if (res) {
          message.success('批量确认成功！');
          this.setState(
            {
              selectedRowKeys: [],
              selectedRows: [],
              isBatchConfirmation: false,
            },
            () => {
              this.getTableData();
            },
          );
        }
      },
    });
  };

  //转非标
  toStandard = () => {
    this.props.dispatch({
      type: 'manAssetManagePlanInfoM/assetManagePlanInfoTranslate',
      payload: { data: this.state.selectedRowKeys },
      callback: (res) => {
        if (res) {
          message.success('转非标确认成功！');
          this.setState(
            {
              selectedRowKeys: [],
              selectedRows: [],
              isBatchConfirmation: false,
            },
            () => {
              // 提示用户“转换成功，请在非标页面补充相关的信息。
              this.getTableData();
              this.props.changeTabRefresh('3');
            },
          );
        }
      },
    });
  };

  //列表点击响应
  onSelectChange = (selectedRowKeys, selectedRows) => {
    let isBatchConfirmation = selectedRowKeys.length > 0;
    this.setState({
      selectedRowKeys,
      selectedRows,
      isBatchConfirmation,
    });
  };

  // 改变columns的样式
  changeColumns = (columns) => {
    const {
      globalM: {
        dataDictionary: { ENTRUSTED_ASSET_TYPE_DICT = [] },
      },
    } = this.props;
    let data = columns;
    if (data && data.length) {
      if (data[data.length - 1].title !== '操作' && !this.state.isHistory) {
        data.push({
          title: '操作',
          dataIndex: 'id',
          key: 'id',
          type: 'operate',
          operates: [
            {
              title: '编辑',
              onClick: (record) => this.addModalOpen('edit', record),
            },
          ],
        });
      }
      data.map((item) => {
        if (item.key == 'assetType') {
          item.render = (text, record) => {
            let temp = '--';
            ENTRUSTED_ASSET_TYPE_DICT.map((item) => {
              if (item.code == text) {
                temp = item.value;
              }
            });
            return temp;
          };
        }
      });
    }
    return data;
  };

  //新增/编辑
  handleOk = () => {
    const {
      form: { validateFields, resetFields },
    } = this.formGroupThis.props;
    const { dispatch } = this.props;
    validateFields((err, fieldsValue) => {
      if (err) return;
      const value = {
        tradingCode: this.state.tradingCode,
        assetType: fieldsValue.assetType,
        isWeiWai: fieldsValue.isWeiWai,
        id: this.state.id,
      };
      dispatch({
        type: 'manAssetManagePlanInfoM/assetManagePlanInfoAdd',
        payload: value,
        callback: (res) => {
          if (res) {
            this.getTableData();
            this.setState({
              tradingCode: '',
              id: undefined,
            });
            this.onCancel();
          }
        },
      });
    });
  };

  //新建根据证券代码回填
  tradingCodeChange = (e) => {
    if (this.state.pageType == 'edit') return;
    if (e) {
      if (e.tradingCode) {
        const {
          form: { setFieldsValue },
        } = this.formGroupThis.props;
        this.setState({
          tradingCode: e.tradingCode,
        });
        this.props.dispatch({
          type: 'manAssetManagePlanInfoM/assetManagePlanInfoDetail',
          payload: {
            tradingCode: e.tradingCode,
            exchangeCode: e.exchangeCode,
          },
          callback: (data) => {
            setFieldsValue({
              assetType: data.assetType,
              isWeiWai: data.isWeiWai,
            });
          },
        });
      } else {
        this.setState({
          tradingCode: e,
        });
      }
    }
  };
  onCancel = () => {
    const {
      form: { validateFields, resetFields },
    } = this.formGroupThis.props;
    this.setState({ visible: false }, () => {
      setTimeout(() => {
        resetFields(); //清空数据
      }, 300);
    });
  };

  //模态框
  showModal = () => {
    const { pageType } = this.state;
    const {
      loading,
      globalM: {
        dataDictionary: { ENTRUSTED_ASSET_TYPE_DICT = [] },
      },
    } = this.props;
    const modalProps = {
      visible: this.state.visible,
      onOk: this.handleOk,
      onCancel: this.onCancel,
      title: pageType == 'edit' ? '编辑' : '新增',
      destroyOnClose: false,
      width: 420,
      maskClosable: false,
      confirmLoading: loading.effects['manAssetManagePlanInfoM/assetManagePlanInfoAdd'] === true || loading.effects['manAssetManagePlanInfoM/assetManagePlanInfoDetail'] === true,
    };
    return (
      <ModalC {...modalProps}>
        <FormGroup
          widthSet={460}
          dataSource={[
            {
              dataIndex: 'tradingCode',
              title: '证券代码',
              type: DATA_ENTRY.SECURITIESCODE,
              initialValue: '',
              disabled: pageType == 'edit' ? true : false,
              rules: [{ required: true, message: '请输入证券代码' }],
              onChange: (e) => {
                this.tradingCodeChange(e);
              },
              codeType: codeType.ZCGLJHandWWTZ,
              isInput: true,
              onRef: (ref) => (this.formGroupThis = ref),
              formItemLayoutDefine,
              positionBody: true,
              span: 24,
            },
            {
              dataIndex: 'assetType',
              title: '资产类别',
              type: DATA_ENTRY.SELECT,
              positionBody: true,
              dataSource: ENTRUSTED_ASSET_TYPE_DICT.map((item) => {
                let obj = {
                  title: item.value,
                  value: item.code,
                };
                return obj;
              }),
              rules: [{ required: true, message: '请选择资产类别' }],
              formItemLayoutDefine,
              span: 24,
            },
            {
              dataIndex: 'isWeiWai',
              title: '是否委外',
              isTrueFalseJudge: true,
              initialValue: '0',
              type: DATA_ENTRY.SELECT,
              formItemLayoutDefine,
              span: 24,
            },
          ]}
          autoLayout={false}
        />
      </ModalC>
    );
  };

  //点击了提示语
  tipClick = (flag) => {
    this.setState(
      {
        flag: flag == true ? '2' : '1',
      },
      () => {
        this.setState(
          {
            isReset: false, // 是否点击重置
            selectedRowKeys: [], // 表格checkbox选择
            selectedRows: [], // 表格checkbox选择
            isBatchConfirmation: false, // 批量确认按钮置灰
            currentPage: 1,
          },
          () => {
            this.getTableData();
          },
        );
      },
    );
  };
  render() {
    const { searchObj, columns, dataSource, currentPage, total, numInPage, selectedRowKeys, isBatchConfirmation, count } = this.state;
    const { loading } = this.props;
    const dataSourceQuery = [
      {
        dataIndex: 'codeName',
        title: '代码或名称',
        type: DATA_ENTRY.INPUT,
        allowClear: true,
      },
      {
        dataIndex: 'isConfirm',
        title: '是否已确认',
        isTrueFalseJudge: true,
        type: DATA_ENTRY.SELECT,
        allowClear: true,
      },
      {
        dataIndex: 'holdDate',
        title: '持仓日期',
        type: DATA_ENTRY.SELECT,
        allowClear: false,
        dataSource: this.state.holdDataList || [],
      },
    ];
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: (record) => {
        if (record.isConfirm == '1') {
          return { disabled: true };
        } else {
          return null;
        }
      },
    };
    const newColumns = this.changeColumns(_.cloneDeep(columns));
    return (
      <div>
        <AdvancedSearch onRef={(ref) => (this.AdvancedSearchRef = ref)} dataSource={dataSourceQuery} onQuery={this.onQuery} onClear={this.onClear}></AdvancedSearch>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '20px' }}>
          <div style={{ display: 'flex', alignContent: 'center' }}>
            {!this.state.isHistory && (
              <div>
                <PrimaryC title='新增' onClick={() => this.addModalOpen('add')}></PrimaryC>
              </div>
            )}
            {!this.state.isHistory && (
              <div style={{ marginLeft: '16px' }}>
                <PrimaryC title='批量确认' onClick={this.confirm} disabled={!isBatchConfirmation}></PrimaryC>
              </div>
            )}
            {!this.state.isHistory && (
              <div style={{ marginLeft: '16px', marginRight: '20px' }}>
                <PrimaryC title='转非标' onClick={this.toStandard} disabled={!isBatchConfirmation}></PrimaryC>
              </div>
            )}
            <div style={{ marginRight: '20px' }}>
              <ExportC
                url={'gateway/instrument-server/regulationInfo/planinfoExport'}
                search={{ ...searchObj, flag: this.state.flag, tenant: this.props.tenant }}
                disabled={dataSource?.length ? false : true}
              />
            </div>
            {!this.state.isHistory && (
              <div style={{ display: 'flex' }}>
                <TipsInfo count={count} handleClick={this.tipClick}></TipsInfo>
              </div>
            )}
          </div>
          {!this.state.isHistory && (
            <div style={{ display: 'flex' }}>
              <RightInfo redTitle={`本月新增标的${this.state.addedThisMonth || 0}只`}></RightInfo>
            </div>
          )}
        </div>
        <div style={{ marginTop: '16px' }}>
          <TableC
            columns={newColumns}
            dataSource={dataSource}
            current={currentPage}
            total={total}
            pageSize={numInPage}
            rowKey='id'
            loading={loading.effects['manAssetManagePlanInfoM/getDataList']}
            scroll={{ x: 'max-content' }}
            onChange={this.handleTableChange}
            rowSelection={!this.state.isHistory ? rowSelection : undefined}
            rowClassName={(record) => {
              return record.createTs == this.state.latestholdDate ? myStyle.redCls : '';
            }}
          ></TableC>
          <div style={{ position: 'absolute', bottom: '16px', left: '0px', display: 'flex' }}></div>
        </div>
        <div>{this.showModal()}</div>
      </div>
    );
  }
}
export default connect(({ manAssetManagePlanInfoM, bondInformationM, globalM, loading }) => ({ manAssetManagePlanInfoM, bondInformationM, globalM, loading }))(AssetManagePlanInfo);
